<template>
  <div class="notice-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>公告管理</span>
          <el-button
              type="primary"
              size="small"
              @click="handleAdd"
              style="float: right;"
          >
            <el-icon><Plus /></el-icon>
            新增公告
          </el-button>
        </div>
      </template>

      <!-- 置顶公告 -->
      <el-card class="top-notice-card" v-if="topNotices.length > 0">
        <template #header>
          <div class="card-header">
            <el-icon><Bell /></el-icon>
            <span style="margin-left: 10px">置顶公告</span>
          </div>
        </template>
        <div
            v-for="notice in topNotices"
            :key="notice.id"
            class="top-notice-item"
            @click="viewNotice(notice)"
        >
          <el-icon color="#ffd700"><Star /></el-icon>
          <span class="top-notice-title">{{ notice.title }}</span>
          <span class="top-notice-time">{{ formatTime(notice.publishTime) }}</span>
        </div>
      </el-card>

      <!-- 公告列表 -->
      <el-table
          :data="notices"
          style="width: 100%; margin-top: 20px;"
          v-loading="loading"
      >
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <span
                :class="{'top-notice-tag': scope.row.isTop === 1}"
                @click="viewNotice(scope.row)"
                style="cursor: pointer;"
            >
              {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="置顶" width="80" align="center">
          <template #default="scope">
            <el-tag
                :type="scope.row.isTop === 1 ? 'danger' : 'info'"
                size="small"
            >
              {{ scope.row.isTop === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
                size="small"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="margin-top: 20px; text-align: center;"
      >
      </el-pagination>
    </el-card>

    <!-- 公告编辑/新增对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        :before-close="handleDialogClose"
    >
      <el-form
          :model="currentNotice"
          :rules="rules"
          ref="noticeFormRef"
          label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="currentNotice.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
              type="textarea"
              :rows="6"
              v-model="currentNotice.content"
              placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch
              v-model="currentNotice.isTop"
              :active-value="1"
              :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 公告查看对话框 -->
    <el-dialog
        :title="viewNoticeData.title"
        v-model="viewDialogVisible"
        width="600px"
    >
      <div class="notice-content-view">
        <div class="notice-meta">
          <span>
            <el-icon><Timer /></el-icon>
            发布时间：{{ formatTime(viewNoticeData.publishTime) }}
          </span>
          <span v-if="viewNoticeData.isTop === 1" style="margin-left: 20px;">
            <el-icon color="#ffd700"><Star /></el-icon>
            置顶公告
          </span>
        </div>
        <div class="notice-content" v-html="viewNoticeData.content"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Bell,
  Star,
  Timer
} from '@element-plus/icons-vue'
import {
  listNotices,
  addNotice,
  updateNotice,
  deleteNotice,
  listTopNotices
} from '@/api/notice'

// 响应式数据
const loading = ref(false)
const notices = ref([])
const topNotices = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const pageInfo = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const currentNotice = reactive({
  id: null,
  title: '',
  content: '',
  isTop: 0,
  publisherId: 1,
  isDeleted: 0,
  publishTime: '' // 改为字符串类型，存储格式化后的时间
})

const viewNoticeData = reactive({
  title: '',
  content: '',
  publishTime: '',
  isTop: 0
})

const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ]
}

const noticeFormRef = ref()

// 获取所有公告
const fetchNotices = async () => {
  loading.value = true
  try {
    const response = await listNotices()
    notices.value = response || []
    pageInfo.total = notices.value.length
  } catch (error) {
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 获取置顶公告
const fetchTopNotices = async () => {
  try {
    const response = await listTopNotices()
    topNotices.value = response || []
  } catch (error) {
    ElMessage.error('获取置顶公告失败')
  }
}

// 查看公告详情
const viewNotice = (notice) => {
  Object.assign(viewNoticeData, notice)
  viewDialogVisible.value = true
}

// 新增公告
const handleAdd = () => {
  dialogTitle.value = '新增公告'
  // 生成当前时间（GMT+8）并格式化为 yyyy-MM-dd HH:mm:ss
  const now = new Date()
  // 计算时区偏移（转成GMT+8）
  const gmt8Time = new Date(now.getTime() + (8 - now.getTimezoneOffset() / 60) * 3600 * 1000)
  Object.assign(currentNotice, {
    id: null,
    title: '',
    content: '',
    isTop: 0,
    publisherId: 1,
    isDeleted: 0,
    publishTime: formatTimeForBackend(gmt8Time) // 存储格式化后的字符串
  })
  dialogVisible.value = true
}

// 编辑公告
const handleEdit = (notice) => {
  dialogTitle.value = '编辑公告'
  // 编辑时保持原时间格式
  Object.assign(currentNotice, {
    ...notice,
    // 确保时间是字符串格式（避免Date对象导致的序列化问题）
    publishTime: typeof notice.publishTime === 'string'
        ? notice.publishTime
        : formatTimeForBackend(new Date(notice.publishTime))
  })
  dialogVisible.value = true
}

// 删除公告
const handleDelete = (notice) => {
  ElMessageBox.confirm('确认删除该公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteNotice(notice.id)
      if (response) {
        ElMessage.success('删除成功')
        fetchNotices()
        fetchTopNotices()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  noticeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保必要字段被设置
        if (!currentNotice.publisherId) {
          currentNotice.publisherId = 1;
        }
        if (currentNotice.isDeleted === undefined) {
          currentNotice.isDeleted = 0;
        }

        // 提交时确保时间格式正确（后端要求的格式）
        if (!currentNotice.id) {
          // 新增时重新确认时间（避免编辑旧时间）
          const now = new Date()
          const gmt8Time = new Date(now.getTime() + (8 - now.getTimezoneOffset() / 60) * 3600 * 1000)
          currentNotice.publishTime = formatTimeForBackend(gmt8Time)
        }

        let response
        if (currentNotice.id) {
          response = await updateNotice(currentNotice)
        } else {
          response = await addNotice(currentNotice)
        }

        if (response) {
          ElMessage.success(currentNotice.id ? '更新成功' : '新增成功')
          dialogVisible.value = false
          fetchNotices()
          fetchTopNotices()
        } else {
          ElMessage.error(currentNotice.id ? '更新失败' : '新增失败')
        }
      } catch (error) {
        ElMessage.error(currentNotice.id ? '更新失败' : '新增失败')
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = (done) => {
  noticeFormRef.value.resetFields()
  done()
}

// 格式化时间为展示用（和后端一致的格式）
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  // 处理时区：确保转换为GMT+8时间
  const gmt8Time = new Date(date.getTime() + (8 - date.getTimezoneOffset() / 60) * 3600 * 1000)
  return `${gmt8Time.getFullYear()}-${
      (gmt8Time.getMonth() + 1).toString().padStart(2, '0')
  }-${
      gmt8Time.getDate().toString().padStart(2, '0')
  } ${
      gmt8Time.getHours().toString().padStart(2, '0')
  }:${
      gmt8Time.getMinutes().toString().padStart(2, '0')
  }:${
      gmt8Time.getSeconds().toString().padStart(2, '0')
  }`
}

// 专门用于给后端提交的时间格式化（确保格式严格匹配）
const formatTimeForBackend = (date) => {
  return `${date.getFullYear()}-${
      (date.getMonth() + 1).toString().padStart(2, '0')
  }-${
      date.getDate().toString().padStart(2, '0')
  } ${
      date.getHours().toString().padStart(2, '0')
  }:${
      date.getMinutes().toString().padStart(2, '0')
  }:${
      date.getSeconds().toString().padStart(2, '0')
  }`
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageInfo.pageSize = val
  fetchNotices()
}

const handleCurrentChange = (val) => {
  pageInfo.currentPage = val
  fetchNotices()
}

// 页面加载时获取数据
onMounted(() => {
  fetchNotices()
  fetchTopNotices()
})
</script>

<style scoped>
.notice-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 100px);
}

.main-card {
  min-height: calc(100vh - 140px);
}

.top-notice-card {
  border: 1px solid #ffd700;
  background-color: #fff9e6;
}

.top-notice-item {
  padding: 10px 0;
  border-bottom: 1px dashed #ebeef5;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.top-notice-item:last-child {
  border-bottom: none;
}

.top-notice-title {
  margin: 0 15px;
  font-weight: 500;
  flex: 1;
}

.top-notice-time {
  color: #909399;
  font-size: 12px;
}

.top-notice-tag::before {
  content: "★ ";
  color: #ffd700;
}

.notice-content-view {
  line-height: 1.8;
}

.notice-meta {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
  color: #606266;
  display: flex;
  align-items: center;
}

.notice-content {
  white-space: pre-wrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>